package com.wman.sheep.mvp.base;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wman.sheep.R;
import com.wman.sheep.adapter.EmptyAdapter;
import com.wman.sheep.common.application.AbsAppConfig;
import com.wman.sheep.rvadapter.BaseQuickAdapter;
import com.wman.sheep.widget.BaseTitleBar;
import com.wman.sheep.widget.refreshlayout.PullRefreshLayout;

import java.util.ArrayList;

/**
 * 下拉列表界面基类
 */
public abstract class BaseListFragment<T extends BaseQuickAdapter, K>
        extends BaseFragment<PullListDelegate>
        implements BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener, PullRefreshLayout.OnRefreshListener {

    protected T mAdapter;
    protected RecyclerView mRecyclerView;
    protected PullRefreshLayout mRecyclerRefreshLayout;
    //顶部渐变的背景
    private View mGradient;
    //TitleBar
    protected BaseTitleBar mTitleBar;
    //Loading 进度条ViewStub
    protected ViewStub mLoadingViewStub;
    //Loading View
    protected View mLoadingView;

    protected View notDataView;

    /**
     * 延时时间
     */
    protected int delayMillis = 100;
    /**
     * 当前页数
     */
    public int mPage = 1;
    /**
     * 数据集
     */
    protected ArrayList<K> mDatas = new ArrayList<>();
    private TextView tvError;
    private ImageView ivError;

    @Override
    protected Class<PullListDelegate> getDelegateClass() {
        return PullListDelegate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
    }

    @Override
    public void fetchData() {
        mRecyclerView = mViewDelegate.get(R.id.recyclerView);
        mRecyclerRefreshLayout = mViewDelegate.get(R.id.refreshlayout);

        mGradient = mViewDelegate.get(R.id.view_gradient);
        mTitleBar = mViewDelegate.get(R.id.include_action_bar);

        mLoadingViewStub = mViewDelegate.get(R.id.loading_viewstub);

        setShowTitleBar();

        initNoDataViewState();

        initAdapter();

        mRecyclerRefreshLayout.setOnRefreshListener(this);
        mRecyclerRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_SMARTISAN);

        addHeadView();

        mPage = 1;
        onRefresh();
    }

    private void initNoDataViewState() {
        notDataView = getActivity().getLayoutInflater().inflate(R.layout.view_empty_layout,
                (ViewGroup) mRecyclerView.getParent(), false);
        tvError = (TextView) notDataView.findViewById(R.id.tv_error_layout);
        ivError = (ImageView) notDataView.findViewById(R.id.img_error_layout);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        notDataView.setVisibility(View.GONE);
    }

    protected void initAdapter() {
        mAdapter = getAdapter();
        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
        // mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        //检查是否满一屏，如果不满足关闭loadMore
        mAdapter.disableLoadMoreIfNotFullPage();
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);

        if (mAdapter instanceof EmptyAdapter) {

        } else {
            mAdapter.setEmptyView(notDataView);
        }
    }

    public void setErrorResource(int rid) {
        if (ivError != null) {
            ivError.setVisibility(View.VISIBLE);
            ivError.setImageResource(rid);
        }
    }

    public void setMsg(String tv) {
        if (tvError != null) {
            tvError.setText(tv);
        }
    }

    protected void addHeadView() {

    }

    /**
     * 获取BasePullUpRecyclerAdapter
     *
     * @return
     */
    protected abstract T getAdapter();

    public BaseTitleBar getBaseTitleBar() {
        if (mTitleBar == null) {
            mTitleBar = mViewDelegate.get(R.id.include_action_bar);
        }
        return mTitleBar;
    }

    /**
     * 显示LoadingView
     */
    public void showLoadingView() {
        mLoadingViewStub.setVisibility(View.VISIBLE);
        mLoadingView = mViewDelegate.get(R.id.loading_view);
    }

    /**
     * 隐藏LoadingView
     */
    public void hideLoadingView() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }

    /**
     * 是否显示TitleBar
     *
     * @return
     */
    protected abstract boolean isShowTitleBar();

    /**
     * 网络数据的请求/处理
     */
    protected abstract void doRequest();

    @Override
    public void onRefresh() {
        mUiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //数据未加载出来再次进行刷新操作需要判空处理
                if (mRecyclerView != null) {
                    mRecyclerView.scrollToPosition(0);
                }
                if (mAdapter != null) {
                    mAdapter.setNewData(mDatas);
                }
                if (mAdapter != null) {
                    mAdapter.setEnableLoadMore(false);
                }
                mPage = 1;
                showRefreshing();
                doRequest();
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        doRequest();
    }

    /**
     * 检查adapter的状态 是否加载更多
     *
     * @param nextIndex 下一页的页数
     */
    protected void checkAdapterLoadMoreStatus(final int nextIndex) {
        checkDataStatus();
        if (nextIndex > mPage) {
            mPage = nextIndex;
            //设置加载完成
            mAdapter.setEnableLoadMore(true);
            mAdapter.loadMoreComplete();
        } else if (mPage == 1 && nextIndex < mPage) {
            mAdapter.setEnableLoadMore(false);
        } else {
            mAdapter.loadMoreEnd();
        }
    }

    /**
     * 检查adapter的状态 是否加载更多
     *
     * @param nextIndex 下一页的页数
     * @param dataSize  请求数据的数量
     */
    protected void checkAdapterLoadMoreStatus(final int nextIndex, final int dataSize) {
        if (dataSize < AbsAppConfig.SAMPLE_LIMIT) {
            checkAdapterLoadMoreStatus(0);
        } else {
            checkAdapterLoadMoreStatus(nextIndex);
        }
    }

    /**
     * 刷新的时候数据源不为空清除数据
     */
    private void checkDataStatus() {
        if (mPage == 1) {
            if (mDatas != null && mDatas.size() > 0) {
                mDatas.clear();
            }
        }
    }

    private void setShowTitleBar() {
        if (isShowTitleBar()) {
            mTitleBar.setVisibility(View.VISIBLE);
            mGradient.setVisibility(View.VISIBLE);
        } else {
            mTitleBar.setVisibility(View.GONE);
            mGradient.setVisibility(View.GONE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mRecyclerRefreshLayout.getLayoutParams();
            lp.setMargins(0, 0, 0, 0);
            mRecyclerRefreshLayout.setLayoutParams(lp);
        }
    }

    /**
     * 显示加载进度条
     */
    public void showRefreshing() {
        if (mRecyclerRefreshLayout == null) {
            return;
        }

        mRecyclerRefreshLayout.setRefreshing(true);
    }

    /**
     * 关闭加载进度条
     */
    public void closeRefreshing() {
        if (mRecyclerRefreshLayout == null) {
            return;
        }

        mRecyclerRefreshLayout.setRefreshing(false);
        if (mPage == 1 && mDatas.size() == 0) {
            notDataView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }
}